<template>
  <div id="order" class="container">
    <div class="flex">
      <div class="left">
        <el-input
          id="attachmentTree"
          v-model="cateTitle"
          placeholder="请输入分类名称"
        >
          <el-button
            slot="append"
            type="primary"
            icon="el-icon-search"
            style="border-radius: 3px; border: none; height: 40px"
            @click="serarchCate"
          />
        </el-input>
        <AttachmentCate ref="AttachmentCate" @update="getList" />
      </div>
      <div class="right">
        <el-tabs
          v-model="activeName"
          class="tabs"
          type="card"
          @tab-click="handleClick"
        >
          <el-tab-pane
            v-for="item in typeList"
            :key="item.id"
            :value="item.id"
            :label="item.label"
          />
        </el-tabs>
        <!-- <el-button type="danger" size="small" icon="el-icon-delete" @click="Batchdelete">批量删除</el-button> -->
        <BouncedDialog
          :title="addForm.id ? '编辑' : '添加'"
          :dialog-show.sync="dialogShow"
          width="50%"
          class="inner"
        >
          <el-tabs v-model="activeName2" type="card">
            <el-tab-pane label="附件上传" name="first1">
              <el-form
                ref="addForm"
                :model="addForm"
                :rules="rules"
                inline
                class="addForm"
                label-width="60px"
              >
                <el-form-item label="文件:">
                  <el-upload
                    v-if="uploadSmall"
                    ref="upload"
                    :headers="myHeaders"
                    class="avatar-uploader"
                    :action="
                      $store.getters.updateURL + '/attachment/uploadAndsave'
                    "
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :auto-upload="true"
                    :file-list="fileList"
                    :multiple="true"
                    :data="uploadData"
                    style="display: inline-block"
                  >
                    <el-button size="small" type="primary">选取文件</el-button>
                  </el-upload>
                  <UploadChunk v-else :dialog-show="dialogShow" />
                </el-form-item>
                <div class="btn">
                  <el-button @click="dialogShow = false">取 消</el-button>
                  <el-button type="primary" @click="submit()">确 定</el-button>
                </div>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="网络附件" name="second1">
              <el-form
                id="urlForm"
                :rules="urlRules"
                :model="urlForm"
                inline
                label-width="60px"
              >
                <el-form-item label="名称:" prop="name">
                  <el-input v-model="urlForm.name" />
                </el-form-item>
                <el-form-item label="地址:" prop="url">
                  <el-input v-model="urlForm.url" />
                </el-form-item>
                <el-form-item label="描述:">
                  <el-input v-model="urlForm.description" type="textarea" />
                </el-form-item>
                <div class="btn">
                  <el-button @click="dialogShow = false">取 消</el-button>
                  <el-button type="primary" @click="submitUrl()">
                    确 定
                  </el-button>
                </div>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </BouncedDialog>
        <BouncedDialog
          :title="'编辑'"
          :dialog-show.sync="dialogShow1"
          width="50%"
          class="inner"
        >
          <el-tabs v-model="activeName3" type="card">
            <el-tab-pane label="修改附件地址" name="editFile">
              <el-form
                id="urlForm1"
                :model="urlForm1"
                inline
                label-width="60px"
              >
                <el-form-item class="form_item" label="名称:" prop="name">
                  <el-input v-model="urlForm1.name" class="form_item_input" />
                </el-form-item>
                <el-form-item class="form_item" label="地址:" prop="url">
                  <span>{{ urlForm1.prefix_url }}</span>
                  <el-input
                    v-model="urlForm1.suffix_url"
                    class="form_item_input"
                  />
                </el-form-item>
                <el-form-item class="form_item" label="描述:">
                  <el-input
                    v-model="urlForm1.description"
                    type="textarea"
                    class="form_item_textarea"
                  />
                </el-form-item>
                <div class="btn">
                  <el-button @click="dialogShow1 = false">取 消</el-button>
                  <el-button type="primary" @click="submitUrl1()">
                    确 定
                  </el-button>
                </div>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </BouncedDialog>
        <div style="padding-top: 20px; background-color: #fff">
          <el-button
            type="primary"
            class="add"
            size="small"
            style="margin-bottom: 15px; margin-left: 15px"
            @click="goAdd"
          >
            添加附件
          </el-button>
          <el-button
            type="primary"
            class="add"
            size="small"
            style="margin-bottom: 15px; margin-left: 15px"
            @click="goAdd2"
          >
            大文件上传
          </el-button>
          <el-table
            :data="orderData"
            border
            stripe
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            @selection-change="handleSelectionChange"
          >
            <!-- <el-table-column type="selection" width="55" /> -->
            <el-table-column v-if="type == 2" label="预览">
              <template slot-scope="scope">
                <el-image
                  style="width: 50px; height: 50px; background-color: #eee"
                  :src="scope.row.url"
                  :preview-src-list="scope.row.list"
                />
              </template>
            </el-table-column>
            <el-table-column v-if="type == 3" label="预览">
              <template slot-scope="scope">
                <!-- {{ scope.row.mime_type }} -->
                <div class="video">
                  <el-dialog
                    width="600px"
                    append-to-body
                    top="20px"
                    :visible.sync="dialogVisible"
                    :title="playvideoName"
                    @closed="closeDialog"
                  >
                    <video
                      id="video"
                      width="100%"
                      autoplay="autoplay"
                      :src="playvideo"
                      :poster="playvideo"
                      controls="controls"
                      preload
                    >
                      您的浏览器不支持 video 标签。
                    </video>
                  </el-dialog>
                  <i
                    class="el-icon-video-play playIcon"
                    @click="handleCheck(scope.row)"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="名称" prop="name" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.name"
                  @focus="getAttachmentData(scope.row)"
                  @blur="updateAttachment(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="文件大小" prop="size" width="150px" />
            <el-table-column label="文件类型" prop="type" width="100px">
              <template slot-scope="scope">
                <span v-if="scope.row.type == 1">压缩包</span>
                <span v-else-if="scope.row.type == 2">图片</span>
                <span v-else-if="scope.row.type == 3">视频</span>
                <span v-else-if="scope.row.type == 4">文档</span>
                <span v-else-if="scope.row.type == 5">音频</span>
              </template>
            </el-table-column>
            <el-table-column
              label="存储方式"
              prop="storage"
              width="100px"
              show-overflow-tooltip
            />
            <el-table-column
              label="文件地址"
              prop="url"
              width="250px"
              show-overflow-tooltip
            />
            <el-table-column label="文件描述" prop="description">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.description"
                  @focus="getAttachmentData(scope.row)"
                  @blur="updateAttachment(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200px" fixed="right">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.suffix_url"
                  class="edit"
                  size="mini"
                  @click="edit(scope.row)"
                >
                  修改文件地址
                </el-button>
                <el-button
                  v-clipboard:copy="scope.row.url"
                  v-clipboard:success="onCopy"
                  v-clipboard:error="onError"
                  class="edit"
                  size="mini"
                >
                  复制链接
                </el-button>
                <el-button class="dele" size="mini" @click="del(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination
          :current-page="page.currentPage"
          :page-sizes="page.pageSizes"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          :hide-on-single-page="page.total < page.size ? true : false"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>
<script>
import attachmentApi from '@/api/system/attachment.js'
import systemApi from '@/api/system/system'
import websiteApi from '@/api/website.js'
import { getToken } from '@/utils/auth'

import log from '@/api/log'
var token1 = 'Bearer ' + getToken()
export default {
  data() {
    return {
      uploadSmall: true,
      dialogVisible: false, // 视频播放弹窗
      playvideo: null, // 存储用户点击的视频播放链接
      playvideoName: null, // 存储正在播放视频的名称
      videoName: '',
      typeList: [
        { label: '全部', id: 0 },
        { label: '压缩包', id: 1 },
        { label: '图片', id: 2 },
        { label: '视频', id: 3 },
        { label: '文档', id: 4 },
        { label: '音频', id: 5 }
      ],
      activeName: '0',
      activeName2: 'first1',
      activeName3: 'editFile',
      type: 0,
      list: [],
      myHeaders: { Authorization: 'Bearer ' + getToken() },
      headers: {},
      siteId: this.$store.getters.siteId,
      imageUrl: '',
      imgUrl: this.$store.getters.updateURL,
      orderData: [], //
      dialogShow: false,
      dialogShow1: false,
      options: [], // 站点下拉选项
      value: '', // 站点下拉框的值
      cateList: '', // 分类列表
      fileList: [], // 文件上传列表
      addForm: {},

      rules: {},
      urlRules: {
        name: [
          { required: 'true', message: '请输入附件名称', trigger: 'blur' }
        ],
        url: [{ required: 'true', message: '请输入附件地址', trigger: 'blur' }]
      },
      urlForm: {
        name: '',
        url: '',
        description: '',
        storage: 5
      },
      urlForm1: {
        id: 0,
        name: '',
        url: '',
        prefix_url: '',
        suffix_url: ''
      },
      searchForm: {
        title: ''
      },
      page: {
        total: 0,
        currentPage: 1,
        size: 10,
        pageSizes: [10, 20, 30, 40]
      }, // 分页器
      val: {},
      id: '',
      cateTitle: '',
      uploadData: {
        type: 0,
        attachment_cate_id: 0
      },
      cate_id: 0,
      attachmentName: '',
      attachmentDescription: '',
      fileSize: '',
      chunkSize: ''
    }
  },
  computed: {
    siteId1() {
      return this.$store.getters.siteId
    }
  },
  watch: {
    siteId1(val, value) {
      if (value) {
        this.getList()
      }
    }
  },
  created() {
    this.getWebsite(this.$store.getters.siteId)
    this.getList()
    this.getUpload()
    // this.getCatelist()
    console.log(this.$store.getters.siteId)
  },
  mounted() {
    // this.getTikets()
  },
  updated() {},
  methods: {
    // 添加网络附件
    submitUrl() {
      const val = []
      val.push(this.urlForm)
      attachmentApi.attachmentSave(val).then(res => {
        if (res.code == 0) {
          this.$message.success(res.msg)
          this.dialogShow = false
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    getWebsite(val) {
      this.options.forEach(el => {
        if (el.id == val) {
          var url = el.domain
          if (el.domain.substring(0, 2) == '--') {
            url = el.domain.substring(2, el.domain.length)
          }
          this.websiteUrl = 'http://' + url
          console.log(this.websiteUrl)
        }
      })
    },
    getUpload() {
      systemApi.sysList().then(res => {
        const data = res.data
        console.log(data[1].children[10].value)
        this.chunkSize = data[1].children[10].value * 1024
      })
    },
    // 搜索附件分类
    serarchCate() {
      this.$refs.AttachmentCate.getCateList(this.cateTitle)
    },
    // 复制到剪切板
    onCopy() {
      this.$message.success('复制成功！')
    },
    onError() {
      this.$message.error('复制失败，请重试！')
    },
    handleCheck(row) {
      this.playvideo = row.url // 存储用户点击的视频播放链接
      this.playvideoName = row.name // 存储用户点击的视频播放链接
      this.dialogVisible = true
      // this.videoName = this.playvideoName
    },
    closeDialog() {},
    // tab切换
    handleClick(val) {
      this.activeName = val.index
      this.uploadData.type = val.index
      this.type = val.index
      this.getList()
    },
    // 上传成功
    handleAvatarSuccess(res, file, fileList) {
      if (res.code == 0) {
        // this.addForm.file = file.response.data
        const arr = []

        fileList.forEach(el => {
          if (el.response) {
            arr.push(el.response.data)
          }
        })
        this.addForm.file = arr
      } else {
        this.$message.error(res.msg)
      }
    },
    upload(row) {
      this.val.id = row.id
      this.val.title = row.title
      this.val.type = row.type
    },
    beforeAvatarUpload(file) {
      console.log(file.size, this.chunkSize)
      const size = file.size * 1
      if (size >= this.chunkSize) {
        this.$message.warning('文件过大，请选择大文件上传')
        // this.uploadSmall = false
        this.dialogShow = false
      } else {
        return true
      }
    },
    // 全选
    handleSelectionChange(val) {},
    // 批量删除
    Batchdelete() {},
    // 获取站点列表
    getWebsiteList() {
      websiteApi.websiteList().then(res => {
        this.options = res.data
      })
    },
    // 选择站点
    chooseWedsite(val) {
      this.$forceUpdate()

      //   this.addForm.id = val
    },
    // 获取文件类别列表
    getCatelist() {
      attachmentApi.cateList().then(res => {
        this.cateList = res.data
      })
    },
    chooseCate(val) {},
    // 新增
    goAdd() {
      this.id = ''
      this.addForm = {}
      this.fileList = []
      this.dialogShow = true
      this.uploadSmall = true
    },
    goAdd2() {
      this.id = ''
      this.addForm = {}
      this.fileList = []
      this.dialogShow = true
      this.uploadSmall = false
    },
    edit(row) {
      this.urlForm1.id = row.id
      this.urlForm1.name = row.name
      this.urlForm1.url = row.url
      this.urlForm1.prefix_url = row.prefix_url
      this.urlForm1.suffix_url = row.suffix_url
      this.urlForm1.description = row.description
      this.dialogShow1 = true
    },
    submitUrl1() {
      attachmentApi.editFileUrl(this.urlForm1).then(res => {
        if (res.code == 0) {
          this.$message.success(res.msg)
          this.dialogShow1 = false
          this.urlForm1 = {
            id: 0,
            name: '',
            url: '',
            prefix_url: '',
            suffix_url: ''
          }
          this.getList()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 编辑
    editor(row) {
      // this.fileList = []
      this.addForm.id = row.id
      this.fileList.splice(0, 1, {
        name: row.name,
        url: 'tihs.imgUrl' + 'row.url'
      })
      this.dialogShow = true
    },
    // 获取内链详情
    getInfo(val) {
      attachmentApi.innerInfo({ id: val }).then(res => {
        this.addForm = res.data
        this.dialogShow = true
      })
    },
    getAttachmentData(data) {
      this.attachmentName = data.name
      this.attachmentDescription = data.description
    },
    // 编辑附件
    updateAttachment(data) {
      const val = {
        id: data.id,
        name: data.name,
        description: data.description
      }
      if (
        this.attachmentName != data.name ||
        this.attachmentDescription != data.description
      ) {
        attachmentApi.attachmentUpdate(val).then(res => {
          if (res.code == 0) {
            this.$message.success(res.msg)
            this.getList()
            this.dialogShow = false
          } else {
            this.$message.error(res.msg)
          }
        })
      }
    },
    submit() {
      this.getList()
      this.dialogShow = false
    },

    // 删除
    del(row) {
      this.$confirm('此操作将删除该附件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          attachmentApi.attachmentDelete({ id: row.id }).then(res => {
            if (res.code == 0) {
              this.$message.success(res.msg)
              this.getList()
            } else {
              this.$message.error(res.msg)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 列表
    getList(cate_id) {
      this.val.page = this.page.currentPage
      this.val.limit = this.page.size
      this.val.type = this.type
      this.val.website_id = this.$store.getters.siteId
      // console.log(cate_id != undefined, '=================')
      if (cate_id != undefined) {
        this.uploadData.attachment_cate_id = cate_id
      }
      this.val.cate_id = this.uploadData.attachment_cate_id
      // this.val.title = this.searchForm.title
      attachmentApi.attachmentList(this.val).then(res => {
        this.orderData = res.data
        this.page.total = res.count
        // this.drawerTableList = res.data
        this.list = []
        // 表格数据  drawerTableList
        // 获取每张图片的地址
        for (var x = 0; x < this.orderData.length; x++) {
          this.list.push(this.orderData[x].url)
        }

        // 根据图片顺序（index）更改每张图片绑定的list的图片顺序
        for (var i = 0; i < this.orderData.length; i++) {
          // this.list.push(this.drawerTableList[i].path)
          var container = this.list

          var frontArr = container.slice(0, i)
          var behindArr = container.slice(i, this.orderData.length)
          var list = behindArr.concat(frontArr)
          this.orderData[i].list = list
        }
      })
    },
    // 分页规格改变
    handleSizeChange(val) {
      this.page.size = val
      this.page.currentPage = 1
      this.getList()
    },
    // 分页点击
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.getList()
    }
  }
}
</script>
<style lang="scss">
#attachmentTree.el-input__inner {
  border-right: none;
}

.tabs.el-tabs--card > .el-tabs__header .el-tabs__item {
  background-color: #eee;
  border: none;
  margin-right: 5px;
}
.tabs.el-tabs--card > .el-tabs__header .el-tabs__item.is-active {
  background-color: #fff;
}
.tabs.el-tabs--card > .el-tabs__header .el-tabs__nav {
  border-radius: 0;
  border: none;
}
.tabs.el-tabs--card .el-tabs__header {
  margin: 0;
}
.tabs.el-tabs--card > .el-tabs__header {
  border-bottom: 0;
}
#order {
  .inner {
    .el-select {
      width: 100%;
    }
  }
  .addForm .el-form-item__content {
    width: calc(100% - 80px);
  }
  .el-upload-list__item {
    transition: none !important;
  }
}
#urlForm.el-form--inline .el-form-item__content {
  width: calc(100% - 60px) !important;
}
</style>
<style scoped lang="scss">
#urlForm {
  .el-form-item {
    width: 100%;
  }
}

.video {
  #viddeo {
    height: 300px;
  }
}
.playIcon {
  font-size: 22px;
  cursor: pointer;
}
.flex {
  width: 100%;
  display: flex;
  justify-content: flex-start;

  .left {
    width: 300px;
    padding: 15px;
    margin-right: 10px;
    background-color: #fff;
  }
  .right {
    width: calc(100% - 310px);
    background-color: #fff;
  }
}
.el-table {
  margin-bottom: 20px;
}
.search {
  min-width: 1350px;
  background-color: #fff;
  padding: 35px 30px 20px;
  border-radius: 5px;
  margin-bottom: 20px;
}
.form_item {
  display: block;

  .form_item_input {
    width: 500px;
  }
  .form_item_textarea {
    width: 500px;
  }
}
</style>
